<template>
  <view class="stats-panel">
    <!-- 面板头部 -->
    <view class="panel-header">
      <view class="header-left">
        <view class="title-section">
          <text class="panel-title">统计信息</text>
          <view class="account-selector" v-if="accounts.length > 1">
            <picker 
              :value="currentAccountIndex" 
              :range="accounts" 
              range-key="nickname"
              @change="handleAccountChange"
            >
              <view class="account-picker">
                <text class="account-name">{{ currentAccount?.nickname || '选择账号' }}</text>
                <text class="picker-icon">▼</text>
              </view>
            </picker>
          </view>
        </view>
        <view class="summary-section">
          <text class="summary-text">成功率: {{ successRate }}%</text>
          <text class="summary-text">盘子: {{ stats.beadTray || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 主要统计卡片 -->
    <view class="stats-cards">
      <view class="stat-card">
        <text class="card-label">总次数</text>
        <text class="card-value">{{ stats.totalAttempts }}</text>
        <view class="card-trend" v-if="stats.totalAttempts > 0">
          <text class="trend-icon">🎯</text>
          <text class="trend-text">成功率 {{ successRate }}%</text>
        </view>
      </view>
      <view class="stat-card">
        <text class="card-label">总灵石</text>
        <text class="card-value">{{ stats.totalStones.toFixed(2) }}</text>
        <view class="card-trend" v-if="stats.successfulPlunders > 0">
          <text class="trend-icon">💎</text>
          <text class="trend-text">平均 {{ averageStones.toFixed(1) }} 灵石/次</text>
        </view>
      </view>
      <view class="stat-card">
        <text class="card-label">成功次数</text>
        <text class="card-value">{{ stats.successfulPlunders }}</text>
        <view class="card-trend" v-if="stats.successfulPlunders > 0">
          <text class="trend-icon">✨</text>
          <text class="trend-text">成功抢夺次数</text>
        </view>
      </view>
    </view>

    <!-- 昵称统计 -->
    <view class="nickname-stats" v-if="hasNicknameStats">
      <view class="section-header">
        <text class="section-title">昵称统计</text>
        <text class="section-subtitle">按抢夺次数排序</text>
      </view>
      <scroll-view class="nickname-list" scroll-y>
        <view 
          v-for="(stat, nickname) in sortedNicknameStats" 
          :key="nickname"
          class="nickname-item"
        >
          <view class="nickname-info">
            <text class="nickname-text">{{ nickname }}</text>
            <view class="nickname-badges">
              <text class="nickname-badge count">{{ stat.count }}次</text>
              <text class="nickname-badge stones">{{ stat.stones.toFixed(1) }}灵石</text>
            </view>
          </view>
          <view class="nickname-progress">
            <view 
              class="progress-bar"
              :style="{ width: `${(stat.count / maxNicknameCount) * 100}%` }"
            ></view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 最近记录 -->
    <view class="recent-records" v-if="hasRecords">
      <view class="section-header">
        <text class="section-title">最近记录</text>
        <text class="section-subtitle">最近 {{ stats.records.length }} 条记录</text>
      </view>
      <scroll-view class="records-list" scroll-y>
        <view 
          v-for="(record, index) in stats.records" 
          :key="index"
          class="record-item"
        >
          <view class="record-time">{{ formatTime(record) }}</view>
          <view class="record-content">
            <view class="record-main">
              <text class="record-nickname">{{ record.nickname }}</text>
              <text class="record-stones">+{{ record.stones.toFixed(1) }}</text>
            </view>
            <view class="record-details">
              <text class="record-target">目标ID: {{ record.targetRoleId }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 无数据提示 -->
    <view v-if="!hasStats" class="empty-stats">
      <text class="empty-icon">📊</text>
      <text class="empty-text">暂无统计数据</text>
      <text class="empty-hint">开始抢夺后将会显示统计信息</text>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue';

const props = defineProps({
  stats: {
    type: Object,
    required: true
  }
});

// 账号相关状态
const accounts = ref([]);
const currentAccountIndex = ref(0);
const currentAccount = computed(() => accounts.value[currentAccountIndex.value] || null);

// 加载账号列表
const loadAccounts = () => {
  try {
    const savedAccounts = uni.getStorageSync('plunder_accounts') || [];
    accounts.value = savedAccounts;
    const currentAccountId = uni.getStorageSync('current_account_id');
    if (currentAccountId) {
      const index = savedAccounts.findIndex(acc => acc.roleId === currentAccountId);
      if (index !== -1) {
        currentAccountIndex.value = index;
      }
    }
  } catch (e) {
    console.error('加载账号列表失败:', e);
    accounts.value = [];
  }
};

// 账号切换处理
const handleAccountChange = (e) => {
  const index = e.detail.value;
  if (index >= 0 && index < accounts.value.length) {
    currentAccountIndex.value = index;
    const account = accounts.value[index];
    if (account) {
      uni.setStorageSync('current_account_id', account.roleId);
      // 触发账号切换事件
      uni.$emit('account-changed', account);
    }
  }
};

// 在组件挂载时加载账号列表
onMounted(() => {
  loadAccounts();
});

// 监听账号变化
watch(() => uni.getStorageSync('current_account_id'), (newId) => {
  if (newId) {
    const index = accounts.value.findIndex(acc => acc.roleId === newId);
    if (index !== -1) {
      currentAccountIndex.value = index;
    }
  }
});

// 时间格式化函数
const formatTime = (record) => {
  if (record.date) {
    // 如果有完整时间戳，使用它
    const date = new Date(record.date);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
  } else if (record.timestamp) {
    // 如果有格式化好的时间戳，直接使用
    return record.timestamp;
  }
  return '--:--:--';  // 默认值
};

// 计算属性
const successRate = computed(() => {
  if (props.stats.totalAttempts === 0) return '0.00';
  return ((props.stats.successfulPlunders / props.stats.totalAttempts) * 100).toFixed(2);
});

const averageStones = computed(() => {
  if (props.stats.successfulPlunders === 0) return 0;
  return props.stats.totalStones / props.stats.successfulPlunders;
});

const hasStats = computed(() => {
  return props.stats && typeof props.stats === 'object';
});

const hasNicknameStats = computed(() => {
  return Object.keys(props.stats.nicknameStats).length > 0;
});

const hasRecords = computed(() => {
  return props.stats.records.length > 0;
});

// 昵称统计排序
const sortedNicknameStats = computed(() => {
  const stats = props.stats.nicknameStats;
  return Object.entries(stats)
    .sort(([, a], [, b]) => b.count - a.count)
    .reduce((obj, [nickname, stat]) => {
      obj[nickname] = stat;
      return obj;
    }, {});
});

// 最大抢夺次数（用于进度条计算）
const maxNicknameCount = computed(() => {
  if (!hasNicknameStats.value) return 1;
  return Math.max(...Object.values(props.stats.nicknameStats).map(stat => stat.count));
});
</script>

<style scoped>
.stats-panel {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.panel-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #2c3e50;
}

.summary-section {
  display: flex;
  gap: 16rpx;
}

.summary-text {
  font-size: 24rpx;
  color: #606266;
  background-color: #f5f7fa;
  padding: 6rpx 16rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  gap: 6rpx;
  font-weight: 500;
}

.summary-text:nth-child(1)::before {
  content: '🎯';
}

.summary-text:nth-child(2)::before {
  content: '💫';
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200rpx, 1fr));
  gap: 20rpx;
  margin-bottom: 24rpx;
}

.stat-card {
  background-color: #f8f9fa;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.stat-card:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-label {
  font-size: 24rpx;
  color: #909399;
  font-weight: 500;
}

.card-value {
  font-size: 40rpx;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.2;
}

.card-trend {
  display: flex;
  align-items: center;
  gap: 6rpx;
  margin-top: 4rpx;
  padding-top: 8rpx;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.trend-icon {
  font-size: 24rpx;
}

.trend-text {
  font-size: 22rpx;
  color: #909399;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 0 4rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.section-subtitle {
  font-size: 24rpx;
  color: #909399;
}

.recent-records {
  margin-bottom: 24rpx;
}

.records-list {
  max-height: 400rpx;
  background-color: #f8f9fa;
  border-radius: 16rpx;
  padding: 16rpx;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.record-item {
  display: flex;
  gap: 16rpx;
  padding: 16rpx;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  transition: background-color 0.2s ease;
}

.record-item:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.record-item:last-child {
  border-bottom: none;
}

.record-time {
  font-size: 24rpx;
  color: #909399;
  font-family: monospace;
  white-space: nowrap;
  padding-top: 4rpx;
}

.record-content {
  flex: 1;
}

.record-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6rpx;
}

.record-nickname {
  font-size: 26rpx;
  color: #2c3e50;
  font-weight: 500;
}

.record-stones {
  font-size: 26rpx;
  font-weight: 600;
  color: #4caf50;
}

.record-details {
  font-size: 22rpx;
  color: #909399;
}

.nickname-stats {
  margin-bottom: 24rpx;
}

.nickname-list {
  max-height: 300rpx;
  background-color: #f8f9fa;
  border-radius: 16rpx;
  padding: 16rpx;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.nickname-item {
  margin-bottom: 16rpx;
  padding: 12rpx;
  border-radius: 8rpx;
  transition: background-color 0.2s ease;
}

.nickname-item:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.nickname-item:last-child {
  margin-bottom: 0;
}

.nickname-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.nickname-text {
  font-size: 26rpx;
  color: #2c3e50;
  font-weight: 500;
}

.nickname-badges {
  display: flex;
  gap: 8rpx;
}

.nickname-badge {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-weight: 500;
}

.nickname-badge.count {
  background-color: #e3f2fd;
  color: #1976d2;
}

.nickname-badge.stones {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.nickname-progress {
  height: 4rpx;
  background-color: #e0e0e0;
  border-radius: 2rpx;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #2196f3, #64b5f6);
  transition: width 0.3s ease;
}

.empty-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48rpx 0;
  color: #909399;
  background-color: #f8f9fa;
  border-radius: 16rpx;
  border: 1px dashed #dcdfe6;
}

.empty-icon {
  font-size: 48rpx;
  margin-bottom: 16rpx;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.empty-hint {
  font-size: 24rpx;
  color: #909399;
}

.account-selector {
  position: relative;
}

.account-picker {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 4rpx 12rpx;
  background: #f5f7fa;
  border-radius: 8rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}

.account-picker:hover {
  background: #e4e7eb;
}

.account-name {
  font-size: 24rpx;
  color: #409eff;
  font-weight: 500;
}

.picker-icon {
  font-size: 20rpx;
  color: #909399;
}

@media screen and (min-width: 768px) {
  .stats-cards {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .nickname-list {
    max-height: 400rpx;
  }
  
  .records-list {
    max-height: 500rpx;
  }

  .stat-card {
    padding: 28rpx;
  }

  .card-value {
    font-size: 44rpx;
  }
}
</style> 